package com.demo.apparel.controller.web;

import com.alibaba.excel.EasyExcel;
import com.demo.apparel.common.Result;
import com.demo.apparel.dto.CategoryDTO;
import com.demo.apparel.dto.ClothesByCategoryDTO;
import com.demo.apparel.dto.web.CategoryPageQueryDTO;
import com.demo.apparel.dto.web.ClothesTypeAddDTO;
import com.demo.apparel.service.web.ClothesAdminService;
import com.demo.apparel.service.web.WebCategoryService;
import com.demo.apparel.vo.CategoryAdminVO;
import com.demo.apparel.vo.PageVO;
import com.demo.apparel.vo.web.CategoryWithSubExportVO;
import com.demo.apparel.vo.web.CategoryWithSubVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/web/categories")
@Tag(name = "衣物分类接口", description = "分类管理")
public class WebCategoryController {

    @Autowired
    private WebCategoryService webCategoryService;

    @Autowired
    private ClothesAdminService clothesAdminService;

    @PostMapping("/add")
    @Operation(summary = "新增分类")
    public Result<?> addCategory(@RequestBody CategoryDTO dto) {
        boolean success = webCategoryService.addCategory(dto);
        if (success) {
            return Result.success("新增大类成功");
        } else {
            return Result.fail("新增大类失败");
        }
    }


    /**
     *
     * @return
     */
    @GetMapping("/list")
    @Operation(summary = "获取所有分类")
    public Result<List<CategoryDTO>> getAllCategories() {
        return Result.success(webCategoryService.getAllCategories());
    }

    /**
     *
     * @param category
     * @param pageNum
     * @param pageSize
     * @return
     */
    @PostMapping("/clothes")
    @Operation(summary = "分页获取某分类下衣服")
    public Result<PageVO<ClothesByCategoryDTO>> getClothesByCategory(@RequestParam int category,
                                                                     @RequestParam(defaultValue = "1") int pageNum,
                                                                     @RequestParam(defaultValue = "10") int pageSize) {
        return Result.success(webCategoryService.getClothesByCategory(category, pageNum, pageSize));
    }

    /**
     *
     * @return
     */
    @GetMapping("/categoryGroup")
    @Operation(summary = "获取分类分组下的衣物列表（不含全部）")
    public Result<List<CategoryAdminVO>> getGroupedClothes() {
        List<CategoryAdminVO> result = clothesAdminService.getClothesGroupedByCategory();
        return Result.success(result);
    }

    @PostMapping("/groupWithSubPage")
    @Operation(summary = "获取分类以及子类的昵称")
    public Result<PageVO<CategoryWithSubVO>> getGroupedCategoryWithSubPage(@RequestBody CategoryPageQueryDTO query) {
        PageVO<CategoryWithSubVO> pageData = webCategoryService.getCategoryWithSubPage(query);
        return Result.success(pageData);
    }

    @PostMapping("/add/type")
    @Operation(summary = "新增子分类")
    public Result<Void> addClothesType(@RequestBody ClothesTypeAddDTO dto) {
        webCategoryService.addClothesType(dto);
        return Result.success();
    }

    /**
     *
     * @param dto
     * @return
     */
    @PutMapping("/type/edit")
    @Operation(summary = "编辑小分类")
    public Result<?> editClothesType(@RequestBody ClothesTypeAddDTO dto) {
        boolean success = webCategoryService.updateClothesType(dto);
        if (success) {
            return Result.success("编辑小类成功");
        } else {
            return Result.fail("编辑小类失败");
        }
    }

    /**
     * 根据大类ID删除大类及其对应的小类
     * @param id 大类ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "根据大类ID删除大类及其对应的小类")
    public Result<?> deleteCategory(@PathVariable String id) {
        boolean success = webCategoryService.deleteCategoryById(id);
        if (success) {
            return Result.success("删除大类成功");
        } else {
            return Result.fail("删除大类失败，可能ID不存在");
        }
    }

    @DeleteMapping("/type/delete/{id}")
    @Operation(summary = "删除小分类")
    public Result<?> deleteClothesType(@PathVariable("id") String id) {
        boolean success = webCategoryService.deleteClothesTypeById(id);
        if (success) {
            return Result.success("删除小类成功");
        } else {
            return Result.fail("删除小类失败");
        }
    }

    @PutMapping("/edit/name")
    @Operation(summary = "编辑大类")
    public Result<?> updateCategoryName(@RequestBody CategoryDTO dto) {
        boolean success = webCategoryService.updateCategoryName(dto.getCategory(), dto.getCategoryName());
        if (success) {
            return Result.success("分类名称修改成功");
        } else {
            return Result.fail("分类名称修改失败");
        }
    }

    @GetMapping("/export")
    @Operation(summary = "导出")
    public void export(HttpServletResponse response) throws IOException {
        List<CategoryWithSubExportVO> list = webCategoryService.getExportData();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        String fileName = URLEncoder.encode("分类导出", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), CategoryWithSubExportVO.class)
                .sheet("分类信息")
                .doWrite(list);
    }


}

